/* eslint-disable no-undef */

const execSync = require('child_process').execSync
const fs = require('fs')

console.log('------------ 开发自动升级package.json版本号 ------------');

const packageJsonStr = fs.readFileSync('./package.json').toString()

try {
    const packageJson = JSON.parse(packageJsonStr)
    // 升级版本号
    const arr = packageJson.version.split('.')

    let [major_no, minor_no, patch_no] = arr

    patch_no = 0 + parseInt(patch_no) + 1

    const newVersion = [major_no, minor_no, patch_no].join('.')
    packageJson.version = newVersion

    console.log(packageJson);

    fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, '\t'))

    fs.writeFileSync(
        require('path').resolve(__dirname, '..', 'src/hooks', 'useVersion.ts'),
        `export default '${newVersion}'\n`
    )

    // add new package.json
    execSync(`git add package.json`)
    execSync(`git add src/hooks/useVersion.ts`)
} catch (e) {
    console.error('处理package.json失败，请重试', e.message);
    process.exit(1)
}